package com.future.mayi.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.adapter.GoodsAdapter;
import com.future.mayi.model.interfaces.OnItemClickListener;
import com.future.mayi.response.ListGoodsResponse;
import com.future.mayi.response.TypeListResponse;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.RecyclerItemDecoration;
import com.future.mayi.view.xrecyclerview.XRecyclerView;
import com.future.mayi.widget.SearchSelectView;

import butterknife.BindView;
import butterknife.OnClick;

/**
 *
 */
public class GoodsListActivity extends BaseActivity implements OnItemClickListener, XRecyclerView.LoadingListener, SearchSelectView.TypeViewListener {


    @BindView(R.id.tv_search)
    EditText tvSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.tv_zh)
    TextView tvZh;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_new)
    TextView tvNew;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.recycler_view)
    XRecyclerView recyclerView;
    @BindView(R.id.ssv)
    SearchSelectView ssv;


    private GoodsAdapter adapter;

    //上新
    public static final int NewStyle = 0;
    //品牌
    public static final int BrandStyle = 1;
    //款式
    public static final int StyleStyle = 2;
    //分期
    public static final int FqStyle = 3;
    //综合
    public static final int Default = 4;
    //综合
    public static final int Coupons = 5;

    private int style = 0;
    private int id = 0;

    public static void startActivity(Context context, int style, int id) {
        Intent intent = new Intent(context, GoodsListActivity.class);
        intent.putExtra("style", style);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }


    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_new_goods);
    }

    @Override
    protected void initView() {
        adapter = new GoodsAdapter(this, recyclerView);
        recyclerView.setHasFixedSize(true);
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 2);
        recyclerView.addItemDecoration(new RecyclerItemDecoration(5, 2));
        linearLayoutManager.setStackFromEnd(false);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
    }


    @SuppressWarnings("unchecked")
    @Override
    protected void initDates() {
        style = getIntent().getIntExtra("style", style);
        id = getIntent().getIntExtra("id", id);
        new HttpRequest<TypeListResponse>()
                .with(this)
                .setApiCode(ApiCst.getSearchInfo)
                .setListener(new HttpRequest.OnNetworkListener<TypeListResponse>() {
                    @Override
                    public void onSuccess(TypeListResponse response) {
                        ssv.setData(response.model);
                        if (style == Default) {
                            select(tvZh);
                        } else if (style == NewStyle) {
                            select(tvNew);
                        } else if (style == BrandStyle) {
                            ssv.selectBrand(id);
                        } else if (style == StyleStyle) {
                            if (!ssv.selectStyle(id)) {
                                cate_id = String.valueOf(id);
                                recyclerView.refresh();
                            }
                        } else if (style == FqStyle) {
                            ssv.selectFq();
                        } else if (style == Coupons) {
                            select(tvZh);
                        }
                    }

                    @Override
                    public void onFail(String message, TypeListResponse response) {

                    }
                })
                .start(new TypeListResponse());
    }

    @Override
    protected void initListener() {
        recyclerView.setLoadingListener(this);
        adapter.setOnItemClickListener(this);
        tvSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyCode == keyEvent.KEYCODE_ENTER) {
                    search(tvSearch.getText().toString());
                }
                return false;
            }
        });
        tvSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(tvSearch.getText())) {
                    if (ivClear.getVisibility() == View.VISIBLE) {
                        ivClear.setVisibility(View.GONE);
                    }
                } else {
                    if (ivClear.getVisibility() == View.GONE)
                        ivClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ssv.setListener(this);
    }

    private String searchContent;

    private void search(String text) {
        if (TextUtils.isEmpty(text)) {
            text = null;
        }

        CommonUtils.hideKeyboard(tvSearch, this);
        page = 0;
        searchContent = text;
        minPrice = 0;
        maxPrice = 0;
        search();
    }


    @OnClick({R.id.iv_title_left, R.id.iv_clear, R.id.ll_zh, R.id.ll_price, R.id.ll_new, R.id.ll_select})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left: {
                onBackPressed();
            }
            break;
            case R.id.iv_clear: {
                tvSearch.setText("");
                search(null);
            }
            break;
            case R.id.ll_zh:
                select(tvZh);
                break;
            case R.id.ll_price:
                select(tvPrice);
                break;
            case R.id.ll_new:
                select(tvNew);
                break;
            case R.id.ll_select:
                ssv.setVisibility(View.VISIBLE);
                break;
        }
    }


    @Override
    public void OnItem(View view, int position) {

    }

    @Override
    public void OnLongItem(View view, int position) {

    }


    @Override
    public void onRefresh() {
        page = 0;
        search();
    }

    @Override
    public void onLoadMore() {
        page++;
        search();
    }

    private int page;
    // 0-综合 1-价格升序 2-价格降序 10-上新降序 11-上新升序
    private int sort = 0;


    private int minPrice = 0;
    private int maxPrice = 0;
    private String brand_id;
    private String cate_id;
    private String quality_id;
    private int is_sales;
    private int is_credit;


    private TextView textView;

    // sort  默认不传为按时间倒序 1-时间 2-热门 3-价格
    // sort_type 排序方式 0-正序 1-倒序
    private void select(TextView textView) {
        Drawable drawable = null;
        if (this.textView == null || this.textView != textView) {
            if (textView == tvZh) {
                sort = 0;
            } else if (textView == tvPrice) {
                sort = 1;
            } else if (textView == tvNew) {
                sort = 10;
            }
        } else {
            if (textView == tvZh) {
                return;
            }
            if (sort == 1 || sort == 2) {
                sort = sort == 1 ? 2 : 1;
            } else if (sort == 10 || sort == 11) {
                sort = sort == 10 ? 11 : 10;
            }

        }

        if (textView == tvNew || textView == tvPrice) {
            if (sort == 1 || sort == 10)
                drawable = getResources().getDrawable(R.drawable.btn_huaxuanshang);
            else
                drawable = getResources().getDrawable(R.drawable.btn_huaxuanxian);
        }

        tvZh.setTextColor(getResources().getColor(R.color.sub_text_color));
        tvPrice.setTextColor(getResources().getColor(R.color.sub_text_color));
        tvNew.setTextColor(getResources().getColor(R.color.sub_text_color));
        tvPrice.setCompoundDrawables(null, null, null, null);
        tvNew.setCompoundDrawables(null, null, null, null);
        textView.setTextColor(getResources().getColor(R.color.main_color));
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            textView.setCompoundDrawables(null, null, drawable, null);
        }

        this.textView = textView;
        page = 0;
        recyclerView.refresh();
    }

    @SuppressWarnings("unchecked")
    private void search() {

//        is_recom	否	int	是否猜你喜欢 -1否 0-首页猜你喜欢 n-商品内猜你喜欢 (n为整数 传入商品ID,默认不传为-1)
//        sort	否	int	排序 0-综合 1-价格升序 2-价格降序 10-上新降序 11-上新升序
//        min_price	否	float	最低价格
//        max_price	否	float	最高价格
//        p	否	int	分页 0开始 1代表第二页 （默认不传为0）
//        psize	否	int	每页条数（默认不传为10）

//        brand_id	否	int	品牌ID
//        cate_id	否	int	品类ID
//        quality_id	否	int	成色ID
//        is_sales	否	int	是否降价 0-否 1-是
//        is_credit	否	int	是否可分期 0-否 1-是

        new HttpRequest<ListGoodsResponse>()
                .with(this)
                .setApiCode(ApiCst.getGoodsList)
                .addParam("is_recom", "-1")
                .addParam("coupon_id", style == Coupons ? id : "")
                .addParam("keywords", searchContent)
                .addParam("sort", sort)
                .addParam("min_price", minPrice)
                .addParam("max_price", maxPrice)
                .addParam("p", page)//分页 默认不传 传1代表第二页
                .addParam("psize", 30)//分页 默认不传 传1代表第二页
                .addParam("brand_id", brand_id)
                .addParam("cate_id", cate_id)
                .addParam("quality_id", quality_id)
                .addParam("is_sales", is_sales)
                .addParam("is_credit", is_credit)
                .setListener(new HttpRequest.OnNetworkListener<ListGoodsResponse>() {
                    @Override
                    public void onSuccess(ListGoodsResponse response) {
                        if (page == 0 && (response.list == null || response.list.size() == 0))
                            toast("未找到相关内容");
                        HCUtils.refreshListForPage(recyclerView, adapter, response.list, page, 10);
                    }

                    @Override
                    public void onFail(String message, ListGoodsResponse response) {
                        page = HCUtils.refreshFail(recyclerView, page, getApplicationContext(), message);
                    }
                }).start(new ListGoodsResponse());
    }


    @Override
    public void onTypeChange(String brand_id, String cate_id, String quality_id, int is_sales, int is_credit, int minPrice, int maxPrice) {
        this.minPrice = minPrice;
        this.maxPrice = maxPrice;
        this.brand_id = brand_id;
        this.cate_id = cate_id;
        this.quality_id = quality_id;
        this.is_sales = is_sales;
        this.is_credit = is_credit;
        recyclerView.refresh();
    }
}
